package com.interceptor;

import com.qf.entity.SystemMnue;
import com.qf.entity.UserEmp;
import com.qf.entity.UserRole;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ResourceBundle;

/**
 * 2019/11/25
 * 郭程鹏
 * gcp1909
 * 面向代码面向君,不负时光不负卿
 */

public class AutherInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        System.out.println("anon："+requestURI);

        HttpSession session = request.getSession();

        UserRole menu = (UserRole) session.getAttribute("menu");

        //判断是否是匿名请求
        ResourceBundle login = ResourceBundle.getBundle("login");

        if (login.containsKey(requestURI)){
            return true;
        }
        ResourceBundle aPublic = ResourceBundle.getBundle("public");

        if (aPublic.containsKey(requestURI)){
            return true;
        }


        //判断当前用户的菜单权限请求中有这个请求路径
        for (SystemMnue systemMnue : menu.getMnueList()) {
            if (requestURI.equals(systemMnue.getMnueUrl())){
                return true;
            }
            for (SystemMnue mnue : systemMnue.getSecondMnue()) {
                if (requestURI.equals(mnue.getMnueUrl())){
                    return true;
                }
            }
        }
        //判断当前用户权限功能
        for (SystemMnue pression : menu.getPressions()) {
            if (requestURI.equals(pression.getMnueUrl())){
                return true;
            }
        }

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print("<script>alert('您的权限不足');window.history.back();</script>");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
